package com.example.waterdispenserm2.mo.gpio;


import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;


import com.example.waterdispenserm2.R;
import com.example.waterdispenserm2.base.BasicsActivity;
import com.example.waterdispenserm2.databinding.ActivityGpioBinding;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class GpioActivity extends BasicsActivity<ActivityGpioBinding> implements GpioSerialProtocolHelper.OnDataReceivedListener {

    private TextView[] digitViews = new TextView[4];
    private ImageView[] ledViews = new ImageView[8];
    private TextView logTextView;
    private GpioSerialProtocolHelper serialHelper;

    private final String[] LED_NAMES = {
            "炒菜", "煲粥", "火锅", "武火", "文火", "烧水", "蒸煮", "煲汤"
    };
    @Override
    public void widgetClick(View v) {

    }

    @Override
    public void setListener() {

    }

    @Override
    public void initView() {
        // 初始化数码管视图
        digitViews[0] = findViewById(R.id.digit_thousands);
        digitViews[1] = findViewById(R.id.digit_hundreds);
        digitViews[2] = findViewById(R.id.digit_tens);
        digitViews[3] = findViewById(R.id.digit_units);

        // 初始化LED视图
        int[] ledIds = {
                R.id.led0, R.id.led1, R.id.led2, R.id.led3,
                R.id.led4, R.id.led5, R.id.led6, R.id.led7
        };
        for (int i = 0; i < ledViews.length; i++) {
            ledViews[i] = findViewById(ledIds[i]);
        }

        // 初始化日志视图
        logTextView = findViewById(R.id.log_text);
        logTextView.setMovementMethod(new ScrollingMovementMethod());

        // 初始化按键
        initButtons();

        // 启动串口通信
        serialHelper = new GpioSerialProtocolHelper(new GpioSerialProtocolHelper.OnDataReceivedListener() {
            @Override
            public void onDisplayData(byte[] displayData) {
                GpioActivity.this.onDisplayData(displayData);
            }

            @Override
            public void onSendComplete() {
                GpioActivity.this.onSendComplete();
            }

            @Override
            public void onLogMessage(String message) {
                appendLog(message);
            }
        });
        serialHelper.startListening();

        appendLog("系统启动，开始监听主机数据...");
    }



    private void initButtons() {
        // 按键ID对应键值
        int[] buttonIds = {
                R.id.btn_power,    // 1-电量/电压
                R.id.btn_timer,    // 2-定时/预约
                R.id.btn_minus,   // 3-减
                R.id.btn_plus,    // 4-加
                R.id.btn_func,    // 5-功能
                R.id.btn_start    // 6-启动
        };

        final String[] buttonNames = {
                "电量/电压", "定时/预约", "减", "加", "功能", "启动"
        };

        for (int i = 0; i < buttonIds.length; i++) {
            Button btn = findViewById(buttonIds[i]);
            final byte keyValue = (byte)(i + 1);
            int finalI = i;
            btn.setOnClickListener(v -> {
                serialHelper.sendKeyValue(keyValue);
                appendLog("发送按键: " + buttonNames[finalI] + " (键值: 0x" + String.format("%02X", keyValue) + ")");
            });
        }
    }



    @Override
    protected ActivityGpioBinding getViewBinding() {
        return ActivityGpioBinding.inflate(LayoutInflater.from(this));
    }

    @Override
    public void onDisplayData(byte[] displayData) {
        runOnUiThread(() -> {
            // 更新数码管显示
            for (int i = 0; i < 4; i++) {
                updateDigitView(digitViews[i], displayData[i]);
            }

            // 更新LED状态
            byte ledByte = displayData[4];
            for (int i = 0; i < 8; i++) {
                boolean isOn = ((ledByte >> (7 - i)) & 1) == 1;
                ledViews[i].setImageResource(isOn ?
                        R.drawable.led_on : R.drawable.led_off);
            }

            // 记录接收数据
            StringBuilder dataLog = new StringBuilder("收到显示数据: ");
            for (byte b : displayData) {
                dataLog.append(String.format("%02X ", b));
            }
            appendLog(dataLog.toString());
        });
    }

    // 数码管显示处理
    private void updateDigitView(TextView view, byte segValue) {
        // 提取段码值 (低7位)
        int digitValue = segValue & 0x7F;
        boolean hasDot = (segValue & 0x80) != 0;

        // 段码转数字 (简化处理)
        char digitChar = ' ';
        switch (digitValue) {
            case 0x3F: digitChar = '0'; break;
            case 0x06: digitChar = '1'; break;
            case 0x5B: digitChar = '2'; break;
            case 0x4F: digitChar = '3'; break;
            case 0x66: digitChar = '4'; break;
            case 0x6D: digitChar = '5'; break;
            case 0x7D: digitChar = '6'; break;
            case 0x07: digitChar = '7'; break;
            case 0x7F: digitChar = '8'; break;
            case 0x6F: digitChar = '9'; break;
            case 0x77: digitChar = 'A'; break;
            case 0x7C: digitChar = 'B'; break;
            case 0x39: digitChar = 'C'; break;
            case 0x5E: digitChar = 'D'; break;
            case 0x79: digitChar = 'E'; break;
            case 0x71: digitChar = 'F'; break;
        }

        view.setText(String.valueOf(digitChar) + (hasDot ? "." : ""));
    }

    @Override
    public void onSendComplete() {
        runOnUiThread(() -> appendLog("按键发送完成"));
    }

    @Override
    public void onLogMessage(String message) {
        runOnUiThread(() -> appendLog(message));
    }

    // 添加日志到视图
    private void appendLog(String message) {
        runOnUiThread(() -> {
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS", Locale.getDefault());
            String timestamp = sdf.format(new Date());
            String logEntry = timestamp + " - " + message + "\n";

            // 保持最近100行日志
            String currentLog = logTextView.getText().toString();
            String[] lines = currentLog.split("\n");
            if (lines.length > 100) {
                StringBuilder sb = new StringBuilder();
                for (int i = lines.length - 99; i < lines.length; i++) {
                    sb.append(lines[i]).append("\n");
                }
                currentLog = sb.toString();
            }

            logTextView.setText(currentLog + logEntry);

            // 自动滚动到底部
            final int scrollAmount = logTextView.getLayout().getLineTop(logTextView.getLineCount())
                    - logTextView.getHeight();
            if (scrollAmount > 0)
                logTextView.scrollTo(0, scrollAmount);
            else
                logTextView.scrollTo(0, 0);
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        serialHelper.release();
        appendLog("系统关闭");
    }

}